package com.zjbd.douyangauth.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.digest.DigestAlgorithm;
import cn.hutool.crypto.digest.Digester;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zjbd.douyangcommoncore.entity.DyUsers;
import com.zjbd.douyangcommoncore.result.Result;
import com.zjbd.douyangcommoncore.service.DyUsersService;
import com.zjbd.douyangcommoncore.vo.DyUsersNamePassVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@Tag(name = "注册接口")
@RestController
@RequestMapping("/douyang/auth/register")
public class RegisterController {

    @Autowired
    private DyUsersService dyUsersService;
    /**
     * 用户名密码注册
     */
    @Operation(summary = "用户名密码注册")
    @PostMapping("/usernamePassword")
    public Result usernamePassword(@Valid @RequestBody DyUsersNamePassVo dyUsersNamePassVo){
        // 用户名是否存在
        QueryWrapper<DyUsers> queryWrapper = new QueryWrapper<DyUsers>()
                .eq("username", dyUsersNamePassVo.getUsername());
        DyUsers one = dyUsersService.getOne(queryWrapper);
        if (one != null){
            return Result.error("用户名已存在");
        }

        DyUsers dyUsers = new DyUsers();
        BeanUtil.copyProperties(dyUsersNamePassVo,dyUsers);

        //生成一个随机数，作为盐值
        String salt = RandomUtil.randomString(16);

        //对密码就行加密
        Digester md5 = new Digester(DigestAlgorithm.MD5);
        //加密
        String md5Pass = md5.digestHex(dyUsers.getPassword() + salt);
        log.info("密码加密成功{}",md5Pass);
        dyUsers.setPassword(md5Pass);
        dyUsers.setSalt(salt);


        dyUsersService.save(dyUsers);
        return Result.success("注册成功");
    }

}
